package com.atguigu.flinkWindow;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 会话窗口分配器会根据活动的元素进行分组. 会话窗口不会有重叠, 与滚动窗口和滑动窗口相比, 会话窗口也没有固定的开启和关闭时间.
 * 	如果会话窗口有一段时间没有收到数据, 会话窗口会自动关闭, 这段没有收到数据的时间就是会话窗口的gap(间隔)
 * @author wky
 * @create 2021-07-16-16:48
 */
public class Time_Session_Windows {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<Tuple2<String, Long>> map = streamSource.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String s) throws Exception {
                String[] split = s.split(" ");
                return Tuple2.of(split[0], Long.valueOf(split[1]));
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = map.keyBy(0);
        // TODO 静态gap 每次开启会话 这个会话会保留的时间 , 每更新一次时间刷新一次  到时候没有数据就会进入下一次会话  每一个key就是一个单独的会话
        //WindowedStream<Tuple2<String, Long>, Tuple, TimeWindow> window = keyedStream.window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)));
        // TODO 动态gap 可以根据输入内容决定窗口时长 当下一次的窗口大小于上一次全部重叠时不生效,若大于重叠部分部分生效
        WindowedStream<Tuple2<String, Long>, Tuple, TimeWindow> window = keyedStream.window(ProcessingTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<Tuple2<String, Long>>() {
            //Random random = new Random();

            @Override
            public long extract(Tuple2<String, Long> stringLongTuple2) {
                //long l = stringLongTuple2.f1 + random.nextInt(9);
                //System.out.println(l);
                return stringLongTuple2.f1*1000;
            }
        }));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        window.process(new ProcessWindowFunction<Tuple2<String, Long>, String, Tuple, TimeWindow>() {
            @Override
            public void process(Tuple tuple, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                String start = sdf.format(new Date(context.window().getStart()));
                String end = sdf.format(new Date(context.window().getEnd()));
                System.out.println("窗口开始时间：" + start);
                System.out.println("窗口结束时间：" + end);
                for (Tuple2<String, Long> element : elements) {
                    out.collect(element.f0);
                }

            }
        }).print();
        senv.execute();


    }
}
